source('code/analysis/load.R')

data = read_dta('data/working/deport-sender.dta') %>%
  mutate(exp = 'deport') %>% 
  bind_rows(read_dta('data/working/defund-sender.dta') %>% mutate(exp = 'defund')) %>% 
  bind_rows(read_dta('data/working/defund-sender-replication.dta') %>% mutate(exp = 'defund-replication') %>% rename(tweet_misleading=misleading)) %>%
  bind_rows(read_dta('data/working/rainforest-sender.dta') %>% mutate(exp = 'rainforest')) %>% 
  bind_rows(read_dta('data/working/daylight-sender.dta') %>% mutate(exp = 'daylight') %>% rename(tweet_misleading=misleading))  %>% 
  bind_rows(read_dta('data/working/defund-hypothetical.dta') %>% mutate(exp = 'defund-hypo')) %>%
  bind_rows(read_dta('data/working/anticipated-persuasion.dta') %>% mutate(exp='anticipated')) %>%
  data_finalize()

confounds = c("unnatural", "demand", "signaling", "misleading", "information", "persuasion", "rationale")
openended = read_dta('data/working/defund-openended.dta') %>%
  mutate(information = ifelse(str_detect(handcoding, 'information'), 1, 0),
         persuasion = ifelse(str_detect(handcoding, 'persuasion'), 1, 0),
         rationale = ifelse(str_detect(handcoding, 'rationale'), 1, 0),
         across(confounds, function (x) replace_na(x, F)),
         choose_rationale = post=='Tweet B',
         excuse = condition=='excuse',
         excuse = as.numeric(excuse)) %>%
  mutate(
  education = ifelse(education %in% c('Professional degree (JD, MD)', 'Doctoral degree', "Master's degree"), 'Post-bachelor degree', education),
  education = factor(education, levels = c('Less than high school degree', 
                                           'High school graduate (high school diploma or equivalent including GED)',
                                           'Some college but no degree',
                                           'Associate degree in college (2-year)',
                                           "Bachelor's degree in college (4-year)",
                                           'Post-bachelor degree')),
  race = ifelse(race == 'Native American, Inuit or Aleut' | race == 'Native Hawaiian/Pacific Islander', 'Other', race),
  race = factor(race, levels = c('Other', 'African American/Black', 'Asian/Asian American', 'Caucasian/White')),
  agesq = age^2) 


create_row = function(data, outcome, outcome_label, d=2) {

  data = data %>% drop_na(outcome)

  mean_c=formatC(mean(data[[outcome]][data$excuse==1], na.rm = T), digits=d, format='f')
  mean_nc=formatC(mean(data[[outcome]][data$excuse==0], na.rm = T), digits=d, format='f')
  

  model=lm(as.formula(str_interp('${outcome}~excuse')), data=data)
  print(nobs(model))
        
  coef=formatC(summary(model)$coefficients[,'Estimate']['excuse'], digits=d, format='f')
  sd=formatC(summary(model)$coefficients[,'Std. Error']['excuse'], digits=d, format='f')
  value=paste0(coef,' (',sd,')')
    

  # pvalue without control
  p_excuse_noexcuse1 = formatC(summary(model)$coefficients[,'Pr(>|t|)']['excuse'], digits=d, format='f')

  # pvalue with control
  model=lm(as.formula(str_interp('${outcome}~excuse+age+I(age^2)+race+hisp+male+education')), data=data)
  p_excuse_noexcuse2 = formatC(summary(model)$coefficients[,'Pr(>|t|)']['excuse'], digits=d, format='f')

  # no treatment effect
  if (outcome %in% c('misleading','demand','signaling', 'openended_misleading')) {
    value = '0.00 (0.00)'
    p_excuse_noexcuse1 = '---'
    p_excuse_noexcuse2 = '---'
  }
  row = paste(outcome_label, mean_nc, mean_c, value, p_excuse_noexcuse1, sep=' & ') %>% paste0('\\\\')
  return(row)
  }
  
data$openended_misleading = NA 
data$openended_misleading[data$exp=='defund-replication'] = 0 
data$openended_misleading[data$exp=='daylight'] = 0 

r1 = create_row(data %>% filter(exp=='defund-replication', join==1),outcome='tweet_misleading', outcome_label='Misleading')
r2 = create_row(data %>% filter(exp=='defund-replication', join==1),outcome='openended_misleading', outcome_label='Misleading about timing')

a = create_row(data %>% filter(exp=='rainforest', join==1),outcome='posted', outcome_label='Scheduled post')
a2 = create_row(data %>% filter(exp=='daylight', join==1),outcome='posted', outcome_label='Scheduled post')
a2m = create_row(data %>% filter(exp=='daylight', join==1),outcome='tweet_misleading', outcome_label='Misleading')
a2mt = create_row(data %>% filter(exp=='daylight', join==1),outcome='openended_misleading', outcome_label='Misleading about timing')

b = create_row(data %>% filter(exp=='anticipated'),outcome='percentage', outcome_label='Estimated share persuaded')

c1 = create_row(openended,outcome='rationale', outcome_label='Social cover')
c2 = create_row(openended,outcome='persuasion', outcome_label='Anticipated persuasion')
c3 = create_row(openended,outcome='information', outcome_label='Information')

c4 = create_row(openended,outcome='unnatural', outcome_label='Unnatural')
c5 = create_row(openended,outcome='misleading', outcome_label='Misleading')
c6 = create_row(openended,outcome='signaling', outcome_label='Signaling')
c7 = create_row(openended,outcome='demand', outcome_label='Experimenter demand')


d1 = create_row(data %>% filter(exp=='defund-hypo',credibility=='credible',join==1,socialmedia %in% c('Facebook','Twitter'),vote!='Donald Trump'), 
                outcome='posted', outcome_label='Willing to post (high cred.)')
d2 = create_row(data %>% filter(exp=='defund-hypo',credibility=='notcredible',join==1,socialmedia %in% c('Facebook','Twitter'),vote!='Donald Trump'), 
                outcome='posted', outcome_label='Willing to post (low cred.)')
d3 = create_row(data %>% filter(exp=='defund-hypo',credibility=='credible',join==1,socialmedia %in% c('Facebook','Twitter'),vote!='Donald Trump'), 
                outcome='sob', outcome_label='Share denying bonus (high cred.)')
d4 = create_row(data %>% filter(exp=='defund-hypo',credibility=='notcredible',join==1,socialmedia %in% c('Facebook','Twitter'),vote!='Donald Trump'), 
                outcome='sob', outcome_label='Share denying bonus (low cred.)')


out = c(
  '\\begin{table} \\centering',
  '\\caption{Interpreting effects of rationale on willingness to post anti-defunding Tweet}',
  '\\label{t:robustness}',
  '\\scalebox{0.92}{\\begin{threeparttable}',
  '\\begin{tabular}{@{\\hspace{5pt}}l@{\\hspace{5pt}}cccc} ',
  '\\toprule', 
  '& \\multicolumn{2}{c}{Mean} & \\multicolumn{2}{c}{Treatment effect} \\\\ \\cmidrule(rr){2-3} \\cmidrule(rr){4-5}',
  ' & No Cover & Cover & Coef.~(s.e.) & $p$-value \\\\',
  '\\midrule',
  str_interp('\\multicolumn{5}{l}{\\textbf{Panel A}: Replication of Exp.~1 (Exp.~1R, $n=535$)} \\\\ \\midrule'),
  str_interp('\\multicolumn{5}{l}{\\textit{Respondent believes Tweet is\\ldots}} \\\\'),
  r1 %>% paste0('\\quad  ', .),
  r2 %>% paste0('\\quad  ', .),
  '\\addlinespace',
  str_interp('\\multicolumn{5}{l}{\\textbf{Panel B}: Rainforest placebo (Aux.~Exp.~2, $n=315$)} \\\\ \\midrule'),
  a %>% paste0('\\quad ', .),
  '\\addlinespace',
  str_interp('\\multicolumn{5}{l}{\\textbf{Panel C}: Daylight saving placebo (Aux.~Exp.~3, $n=524$)} \\\\ \\midrule'),
  a2 %>% paste0('\\quad ', .),
  str_interp('\\multicolumn{5}{l}{\\textit{Respondent believes Tweet is\\ldots}} \\\\'),
  a2m %>% paste0('\\quad  ', .),
  a2mt %>% paste0('\\quad  ', .),
  '\\addlinespace',
  str_interp('\\multicolumn{5}{l}{\\textbf{Panel D}: Anticipated persuasion (Aux.~Exp.~4, $n=501$)} \\\\ \\midrule'),
  b %>% paste0('\\quad ', .),
  '\\addlinespace',
  str_interp('\\multicolumn{5}{l}{\\textbf{Panel E}: Open-ended motive elicitation (Aux.~Exp.~5, $n=402$)} \\\\ \\midrule'),
  str_interp('\\multicolumn{5}{l}{\\textit{E.1: Primary motives: respondent mentions\\ldots}} \\\\'),
  c1 %>% paste0('\\quad  ', .),
  c2 %>% paste0('\\quad  ', .),
  c3 %>% paste0('\\quad  ', .),
  '\\addlinespace',
  str_interp('\\multicolumn{5}{l}{\\textit{E.2: Potential confounds: respondent mentions\\ldots}} \\\\'),
  c4 %>% paste0('\\quad  ', .),
  c5 %>% paste0('\\quad  ', .),
  c6 %>% paste0('\\quad  ', .),
  c7 %>% paste0('\\quad  ', .),
  '\\addlinespace',
  str_interp('\\multicolumn{5}{l}{\\textbf{Panel F}: Credibility manipulation (Aux.~Exp.~6, $n=1,017$)} \\\\ \\midrule'),
  str_interp('\\multicolumn{5}{l}{\\textit{F.1: Hypothetical willingness to post}} \\\\'),
  d1 %>% paste0('\\quad ', .),
  d2 %>% paste0('\\quad ', .),
  '\\addlinespace',
  str_interp('\\multicolumn{5}{l}{\\textit{F.2: Beliefs about social sanctions}} \\\\'),
  d3 %>% paste0('\\quad ', .),
  d4 %>% paste0('\\quad ', .), 
  '\\bottomrule',
  '\\end{tabular}',
  '\\begin{tablenotes} \\footnotesize',
  paste0('\\item \\textit{Notes:} ',tablenotes['robustness']),
  '\\end{tablenotes} \\end{threeparttable}} \\end{table}'
)

## Table 2 ##
write_lines(out, str_interp('output/tables/robustness.tex'))



